<?php
/**
 * A simple tag cloud
 * 
 * @author Magnus Stoveland <mstoveland@gmail.com>
 */
class TagCloud {
    
	// Change these font sizes if you will
	var $max_size = 250; // max font size in %
	var $min_size = 100; // min font size in %

	function getCloud() {
	    $tags = $this->getModel();
	    $this->calculateSizes($tags);
	    return $tags;
	}
	
	/**
	 * Get data from the tags table
	 * 
	 * @return array $tags
	 */
    function getModel() {
	    $query = "SELECT * FROM tags ORDER BY hits DESC LIMIT 16";
	    $db = Database::getInstance();
		$result = $db->query($query);
	    while($row = mysql_fetch_array($result)) {
	        //$weights[] = $row['hits'];
	        $tags[] = $row;
	    }
	    // Sort the model on name (can't change the sql because of LIMIT)
        // A better solution?
	    foreach($tags as $row) {
	        $tagsTemp[$row['name']] = $row;
	    }
	    sort($tagsTemp);
	    foreach($tagsTemp as $row) {
	        $tagsRand[$row['id']] = $row;
	    }
	    return $tagsRand;
    }
    
    /**
     * Calculate sizes of each tag
     *
     * @param array &$tags
     */
    function calculateSizes(&$tags) {
    	// Set the largest and smallest array values
        foreach($tags as $tag) {
            $weights[] = $tag['hits'];
        }
		$max_hits = max(array_values($weights));
		$min_hits = min(array_values($weights));
		$spread = $max_hits - $min_hits;
    	if ($spread == 0) { // We don't want to divide by zero
	        $spread = 1;
	    }
	    $step = ($this->max_size - $this->min_size)/($spread);
        foreach($tags as $id => $row) {
            $size = $this->min_size + (($row['hits'] - $min_hits) * $step);
            $tags[$id]['size'] = $size;
        }
    }
    
    /**
     * Updates the weight of the tag (when someone uses it)
     * 
     * @param $tagName
     */
    function updateWeight($tagName) {
        $query = "UPDATE tags SET hits=hits+1 WHERE name='".$tagName."'";
        $db = Database::getInstance();
	    $result = $db->query($query);
    }
    
    /**
     * Add a new tag
     * 
     * @param $tagName
     */
    function addTag($tagName) {
        $query = "INSERT INTO tags (name,hits) VALUES ('".$tagName."', 1)";
        $db = Database::getInstance();
	    $result = $db->query($query);
    }
}
?>